#!/usr/bin/python3
"""
Create a squashfs named `filename`.

Buildhost commands used: `mksquashfs` and any needed compression program.
"""

import os
import subprocess
import sys

import osbuild.api


SCHEMA_2 = """
"options": {
  "additionalProperties": false,
  "required": ["filename"],
  "properties": {
    "filename": {
      "description": "Filename for tar archive",
      "type": "string"
    },
    "compression": {
      "type": "object",
      "additionalProperties": false,
      "required": ["method"],
      "properties": {
        "method": {
          "enum": ["gzip", "xz"]
        },
        "options": {
          "type": "object",
          "additionalProperties": false,
          "properties": {
            "bcj": {
              "enum": [
                "x86",
                "arm",
                "armthumb",
                "powerpc",
                "sparc",
                "ia64"
              ]
            }
          }
        }
      }
    }
  }
},
"inputs": {
  "type": "object",
  "additionalProperties": false,
  "required": ["tree"],
  "properties": {
    "tree": {
      "type": "object",
      "additionalProperties": true
    }
  }
}
"""


def main(inputs, output_dir, options):
    source = inputs["tree"]["path"]
    filename = options["filename"].lstrip("/")
    compression = options.get("compression")

    target = os.path.join(output_dir, filename)

    cmd = ["mksquashfs", source, target]

    if compression:
        method = compression["method"]
        opts = compression.get("options", {})
        cmd += ["-comp", method]
        for opt, val in opts.items():
            cmd += [f"-X{opt}", val]

    subprocess.run(cmd, check=True)

    return 0


if __name__ == '__main__':
    args = osbuild.api.arguments()
    r = main(args["inputs"], args["tree"], args["options"])
    sys.exit(r)
